package com.kehutong.contact.admin;

import com.kehutong.common.ExcelUtil;
import com.kehutong.common.entity.Root;
import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.Contact;
import com.kehutong.contact.entity.ContactDynamics;
import com.kehutong.contact.service.ContactService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.Page;

import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author liujinwang
 * description:联系人
 */
@MvcAction
@ReqMapping("/admin/crm/contact")
public class ContactController {

    static final Logger logger = LoggerFactory.getLogger(ContactController.class);

    @Inject
    private ContactService contactService;

    @ReqMapping("/page")
    public Page<Contact> page(JSONObject jsonObject) throws Exception {
        return contactService.page(jsonObject);
    }

    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
        return contactService.list(jsonObject);
    }

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(Contact contact) throws Exception{
        return contactService.save(contact);
    }

    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(Contact contact) throws Exception {
        return contactService.update(contact);
    }

    /**
     * 删除单个/批量删除
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ReqMapping("/delete")
    public Object delete(JSONObject jsonObject) throws Exception{
        return contactService.delete(jsonObject);
    }

    @ReqMapping("/get")
    public Object get(Contact contact) throws Exception{
        contact = Pool.get(Contact.class, contact.getId());
        return Result.success(contact);
    }

    /**
     * 客户联系人列表
     * @param jsonObject
     * @return
     */
    @ReqMapping("/contactList")
    public Object contactList(JSONObject jsonObject) {
        return contactService.getContactList(jsonObject);
    }

    /**
     *设置首联系人
     * @param jsonObject
     * @return
     */
    @ReqMapping("/update/firstContact")
    public Object updateFirstContact(JSONObject jsonObject) {
        return contactService.updateFirstContact(jsonObject);
    }

    /**
     * 导出联系人数据
     *
     * @param jsonObject 条件对象
     * @return 文件
     * @throws Exception 异常
     */
    @ReqMapping("/export")
    public Object exportData(JSONObject jsonObject, Token token) throws Exception {
        if (!Root.isRoot(token.getUuid())) {
            jsonObject.put("exportUsername",token.getUsername());
        }
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<Contact> page = contactService.page(jsonObject);
        File dataFile = exportDataFile(page.getList());
        return com.kehutong.common.errcode.Result.download(dataFile);
    }

    private File exportDataFile(List<Contact> list) throws Exception{
        Workbook wb = exportWorkBook(list);
        return ExcelUtil.writeXlsFile(wb, "联系人列表_" + System.currentTimeMillis(), ".xls");
    }
    private Workbook exportWorkBook(List<Contact> list) {

        // 生成模板文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        //dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Sheet sheet = wb.createSheet();
        Row headerRow = sheet.createRow(0);
        int headerCellNum = 0;

            String[] chargeUserInstrument = {"联系人姓名", "手机号码", "关联客户","性别","职位","角色","生日","最后联系"};
            for (String s : chargeUserInstrument) {
                Cell cell = headerRow.createCell(headerCellNum++);
                cell.setCellValue(s);
            }
            int cellNum = 0;
            for (int i = 0; i < list.size(); i++) {
                Contact contact = list.get(i);
                Row row = sheet.createRow(i + 1);
                cellNum = 0;
                row.createCell(cellNum++).setCellValue(contact.getContactName());
                row.createCell(cellNum++).setCellValue(contact.getMobile());
                row.createCell(cellNum++).setCellValue(contact.getCorpFullName());
                String sirOrLady = contact.getSirOrLady();
                if ("1".equals(sirOrLady)) {
                    row.createCell(cellNum++).setCellValue("男");
                } else if ("2".equals(sirOrLady)) {
                    row.createCell(cellNum++).setCellValue("女");
                } else {
                    row.createCell(cellNum++).setCellValue("未知");
                }
                row.createCell(cellNum++).setCellValue(contact.getPosition());
                row.createCell(cellNum++).setCellValue(contact.getRole().getDesc());
                row.createCell(cellNum++).setCellValue(contact.getBirthday().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                row.createCell(cellNum++).setCellValue(contact.getLastFollowUpTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            // 自动列宽
            for (int i = 0; i < cellNum; i++) {
                if (i == 0) {
                    // id列不调整
                    continue;
                }
                // 自动列宽
                ExcelUtil.autoSizeColumn(sheet, i);
            }

        return wb;
    }

}
